package com.lbd.util;

import java.io.UnsupportedEncodingException;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.Map;
import java.util.stream.Collectors;

import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;

/**
 * Created by wang on 2016/9/29.
 */
public class HttpClientUtil {
    private static PoolingHttpClientConnectionManager cm;
    private static String EMPTY_STR = "";
    private static String UTF_8 = "UTF-8";
    private static Logger log = Logger.getLogger(HttpClientUtil.class);

    private static void init() {
        if (cm == null) {
            cm = new PoolingHttpClientConnectionManager();
            cm.setMaxTotal(50);// 整个连接池最大连接数
            cm.setDefaultMaxPerRoute(5);// 每路由最大连接数，默认值是2
        }
    }

    /**
     * 通过连接池获取HttpClient
     *
     * @return
     */
    private static CloseableHttpClient getHttpClient() {
        init();
        return HttpClients.custom().setConnectionManager(cm).build();
    }

    /**
     * 1. httpGet请求
     *
     * @param url
     * @return
     */
    private static String httpGetRequest(String url) throws URISyntaxException {
        //原
//        HttpGet httpGet = new HttpGet(url);
//        return getResult(httpGet);
        //新
        return httpGetRequest(url, null, null);
    }

    /**
     * 2. httpGet请求
     *
     * @param url
     * @param params
     * @return
     * @throws URISyntaxException
     */
    private static String httpGetRequest(String url, Map<String, Object> params) throws URISyntaxException {
        //原
//        URIBuilder ub = new URIBuilder();
//        ub.setPath(url);
//
//        ArrayList<NameValuePair> pairs = covertParams2NVPS(params);
//        ub.setParameters(pairs);
//
//        HttpGet httpGet = new HttpGet(ub.build());
        //return getResult(httpGet);

        //新
        return httpGetRequest(url, params, null);
    }

    /**
     * 3. httpGet请求
     *
     * @param url
     * @param params
     * @param headers
     * @return
     * @throws URISyntaxException
     */
    private static String httpGetRequest(String url, Map<String, Object> params, Map<String, Object> headers) throws URISyntaxException {
        URIBuilder ub = new URIBuilder();
        ub.setPath(url);

        ArrayList<NameValuePair> pairs = covertParams2NVPS(params);
        ub.setParameters(pairs);

        HttpGet httpGet = new HttpGet(ub.build());
        if (headers != null) {
            for (Map.Entry<String, Object> param : headers.entrySet()) {
                httpGet.addHeader(param.getKey(), String.valueOf(param.getValue()));
            }
        }
        return getResult(httpGet);
    }

    /**
     * 4. httpPost请求
     *
     * @param url
     * @return
     * @throws UnsupportedEncodingException
     */
    private static String httpPostRequest(String url) throws UnsupportedEncodingException {
        //原
//        HttpPost httpPost = new HttpPost(url);
//        return getResult(httpPost);
        //新
        return httpPostRequest(url, null, null);
    }

    /**
     * 5. httpPost请求
     *
     * @param url
     * @param params
     * @return
     * @throws UnsupportedEncodingException
     */
    private static String httpPostRequest(String url, Map<String, Object> params) throws UnsupportedEncodingException {
        //原
//        HttpPost httpPost = new HttpPost(url);
//        ArrayList<NameValuePair> pairs = covertParams2NVPS(params);
//        httpPost.setEntity(new UrlEncodedFormEntity(pairs, UTF_8));
//        return getResult(httpPost);
        //新
        return httpPostRequest(url, params, null);
    }

    /**
     * 6. httpPost请求
     *
     * @param url
     * @param params
     * @param headers
     * @return
     * @throws UnsupportedEncodingException
     */
    private static String httpPostRequest(String url, Map<String, Object> params, Map<String, Object> headers) throws UnsupportedEncodingException {
        HttpPost httpPost = new HttpPost(url);

        if (headers != null) {
            for (Map.Entry<String, Object> param : headers.entrySet()) {
                httpPost.addHeader(param.getKey(), String.valueOf(param.getValue()));
            }
        }

        ArrayList<NameValuePair> pairs = covertParams2NVPS(params);
        httpPost.setEntity(new UrlEncodedFormEntity(pairs, UTF_8));

        return getResult(httpPost);
    }

    private static ArrayList<NameValuePair> covertParams2NVPS(Map<String, Object> params) {
        ArrayList<NameValuePair> pairs = new ArrayList<>();
        if (params != null) {
            pairs.addAll(params.entrySet().stream().map(param -> new BasicNameValuePair(param.getKey(), String.valueOf(param.getValue()))).collect(Collectors.toList()));
        }
        return pairs;
    }

    /**
     * 7. 处理Http请求
     *
     * @param request
     * @return
     */
    private static String getResult(HttpRequestBase request) {
        // CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpClient httpClient = getHttpClient();
        try {
            CloseableHttpResponse response = httpClient.execute(request);
            // response.getStatusLine().getStatusCode();
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                // long len = entity.getContentLength();// -1 表示长度未知
                String result = EntityUtils.toString(entity);
                response.close();
                // httpClient.close();
                return result;
            }
        } catch (Exception e) {
            log.warn("获取相应结果失败", e);
        }
        return EMPTY_STR;
    }

    /**
     * 1.1 Http请求处理类
     *
     * @param url        访问URL
     * @param httpMethod 访问方式
     * @return
     * @throws URISyntaxException
     * @throws UnsupportedEncodingException
     */
    public static String httpRequest(String url, HttpMethod httpMethod) throws URISyntaxException, UnsupportedEncodingException {
        if (httpMethod.equals(HttpMethod.GET)) {
            return httpGetRequest(url);
        } else {
            return httpPostRequest(url);
        }
    }

    /**
     * 1.2 Http请求处理类
     *
     * @param url        访问URL
     * @param params     参数map
     * @param httpMethod 访问方式
     * @return
     * @throws URISyntaxException
     * @throws UnsupportedEncodingException
     */
    public static String httpRequest(String url, Map<String, Object> params, HttpMethod httpMethod) throws URISyntaxException, UnsupportedEncodingException {
        if (httpMethod.equals(HttpMethod.GET)) {
            return httpGetRequest(url, params);
        } else {
            return httpPostRequest(url, params);
        }
    }

    /**
     * 1.3 Http请求处理类
     *
     * @param url        访问URL
     * @param params     参数map
     * @param headers    headerMap
     * @param httpMethod 访问方式
     * @return 请求结果
     * @throws URISyntaxException
     * @throws UnsupportedEncodingException
     */
    public static String httpRequest(String url, Map<String, Object> params, Map<String, Object> headers, HttpMethod httpMethod) throws URISyntaxException, UnsupportedEncodingException {
        if (HttpMethod.GET.equals(httpMethod)) {
            return httpGetRequest(url, params, headers);
        } else {
            return httpPostRequest(url, params, headers);
        }
    }
}
